package com.thinkit.processor.message;

import com.thinkit.processor.channel.BaseChannelService;
import com.thinkit.processor.license.LicenseProperties;
import com.thinkit.processor.resove.MessageResolveHandler;
import com.thinkit.utils.properties.ThinkItProperties;
import com.thinkit.utils.utils.Checker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class RedisMessage extends MessageHandler {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ThinkItProperties thinkItProperties;

    @Autowired
    LicenseProperties licenseProperties;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<Object> serializer = redisTemplate.getValueSerializer();
        Object msg = serializer.deserialize(message.getBody());
        MessageModel messageModel =new MessageModel(msg,new String(message.getChannel()));
        if(verifyLicense(msg)){
            submit(new MessageResolveHandler(messageModel,thinkItProperties));
        }else{
            log.error("license is invalid,please check license already exists locally or valid!");
        }
    }

    @Autowired
    public void channelService(List<BaseChannelService> baseChannelServices){
        if(Checker.BeNotEmpty(baseChannelServices)){
            for(BaseChannelService channelService:baseChannelServices){
                channelServiceMap.put(channelService.getName().getCode(),channelService);
            }
        }
    }
}
